package com.taxi.driver.module.pay;

import android.content.Context;

import com.qianxx.utils.Logger;
import com.qianxx.utils.ToastUtil;
import com.taxi.driver.common.AppConfig;
import com.taxi.driver.data.entity.WxpayInfo;
import com.taxi.driver.event.PayEvent;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

public class WxPayUtils {

    private static Context mContext;
    private static WxPayUtils instance;
    private static IWXAPI msgApi;
    static PayReq req;

    public static WxPayUtils getInstance(Context context) {
        mContext = context;
        msgApi = WXAPIFactory.createWXAPI(mContext, AppConfig.WX_APPID);
        req = new PayReq();
        msgApi.registerApp(AppConfig.WX_APPID);
        if (instance == null) {
            synchronized (WxPayUtils.class) {
                if (instance == null) {
                    instance = new WxPayUtils();
                }
            }
        }

        return instance;
    }

    private void sendPayReq() {
        msgApi.registerApp(AppConfig.WX_APPID);
        msgApi.sendReq(req);
    }

    private WxpayInfo info;

    /**
     * 微信支付
     */
    public void pay(WxpayInfo info) {
        if (info == null) {
            Logger.d("WxPayUtils--传入的WxpayInfo为空");
            return;
        }
        this.info = info;
        boolean isPaySupported = msgApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (!isPaySupported) {
            ToastUtil.getInstance().toast("您的手机没有安装微信或者微信版本过低");
            EventBus.getDefault().post(new PayEvent(PayEvent.PAY_REMOVE));
            return;
        }
        genPayReqNew();
        sendPayReq();
    }

    private void genPayReqNew() {
        req.appId = info.getAppid();
        req.partnerId = info.getPartnerid();
        req.prepayId = info.getPrepayid();
        req.packageValue = info.getPkg();
        req.nonceStr = info.getNoncestr();
        req.timeStamp = info.getTimestamp();
        req.sign = info.getSign();
    }

}
